<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Api;

class Service
{

    protected static $version = 'V1';
    protected static $apiName;

    // 调用接口
    public static function call($apiName, $param)
    {
        $version = self::$version;
        self::$apiName = $apiName;

        // 检查接口文件
        $apiFile = __DIR__ . "/$version/$apiName.class.php";
        if (!file_exists($apiFile)) {
            return self::_response('invalid_action');
        }

        // 接口方法对象
        $apiClass = "\\Service\\Api\\$version\\$apiName";
        $apiInstance = new $apiClass();

        try {
            filter($param, $apiInstance->input);
            $api_token = $_SERVER['HTTP_API_TOKEN'] ?: $param['api_token'];
            $uid = $api_token ? O('user')->decodeToken($api_token) : false;
            $login_info = $uid ? O('user')->getDetail($uid) : false;
            $uid = $login_info ? $uid : false;//防止用户被删
            if ($apiInstance->login && !($uid && $login_info)) {
                return self::_response('not_login');
            }

            // 执行
            $output = $apiInstance->run($param, $uid, $login_info);
            if ($apiInstance->output) {
                self::filterOutput($output, $apiInstance->output);
            }
            return self::_response('ok', $output);
        } catch (\Exception $e) {
            return self::_response($e->getMessage(), null, $e->getCode());
        }
    }

    //过滤输出
    public static function filterOutput(&$data, $format)
    {
        if (!$data || !is_array($data)) {
            return;
        }

        $format_keys = array_keys((array)$format);
        $arr_format = (count($format_keys) == 1 && $format_keys[0] === 0) ? 'is_num_arr' : 'is_index_arr';

        foreach ($data as $key => $val) {
            if ($arr_format == 'is_index_arr') {
                if (!isset($format[$key])) {
                    unset($data[$key]);
                    continue;
                }

                if (is_array($val)) {
                    self::filterOutput($data[$key], $format[$key]);
                }
            } else if ($arr_format == 'is_num_arr') {
                self::filterOutput($data[$key], $format[0]);
            }
        }
    }

    // 输出测试文档
    public function doc($urlBase, $hosts = [], $version = 'V1')
    {
        return Doc::html($urlBase, $hosts, $version);
    }

    // 格式化响应
    protected static function _response($status, $data = null, $code = 0)
    {
        $codes = Code::$V1;

        // 默认输出系统错误
        $error_code = isset($codes[$status]) ? $status : 'default_error';
        $response = array(
            'api_name' => self::$apiName,
            'request_time' => date('Y-m-d H:i:s'),
            'error_code' => $code ?: $codes[$error_code][0],
            'error_msg' => isset($codes[$status]) ? $codes[$status][1] : $status,
            'data' => $data
        );
        return json_encode($response, JSON_UNESCAPED_UNICODE);
    }
}